package org.shock.ss.sms.action;

import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import org.shock.ss.sms.commons.db.ProxoolDbPool;
import org.shock.ss.sms.commons.utils.Util;

/**
 * 公用的下载类
 * 
 * @author server
 * @since 2010-09-18
 */
@SuppressWarnings("serial")
public class DownLoadAction extends ActionSupport {

	private String sql;// 存放在数据库中的获取BLOB类型的数据库语句
	private String fileName;// 存放的文件名
	private Blob blob;
	private String result;// 系统响应
	private String oldName;// 原文件名
	private int flag;// 0-文件夹下的下载,1-数据库中的BLOB下载
	private String where;// 文件存放在文件夹中的位置

	/**
	 * 进行下载类型判断
	 */
	public String execute() {
		if (Util.isEmpty(fileName)) {
			result = "输入错误";
			return INPUT;
		}
		if (flag == 0) {// 文件夹下的文件下载
			return findFileFromFolder();
		} else {
			return findFileFromDatabase();
		}
	}

	/**
	 * 从数据库中读取文件
	 * 
	 * @return
	 */
	public String findFileFromDatabase() {
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			conn = ProxoolDbPool.getConnection();
			stmt = conn.prepareStatement(sql);
			rs = stmt.executeQuery();
			while (rs.next()) {
				blob =rs.getBlob(1);
			}
		} catch (Exception e) {
			result = "<font color='red'>您访问的资源不存在，请核实！</font>";
			return INPUT;
		} finally {
			ProxoolDbPool.closeResultSet(rs);
			ProxoolDbPool.closeStatement(stmt);
			ProxoolDbPool.closeConnection(conn);
		}
		return SUCCESS;
	}

	/**
	 * 从文件夹下查找文件
	 * 
	 * @return
	 */
	public String findFileFromFolder() {
		if (!isExists(fileName, where)) {
			result = "<font color='red'>您访问的资源不存在，请核实！</font>";
			return INPUT;
		}
		return SUCCESS;
	}

	public InputStream getInputStream() throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/x-download");
		response.addHeader("Content-Disposition", "attachment;filename="
				+ URLEncoder.encode(fileName, "UTF-8"));
		return blob == null ? null : blob.getBinaryStream();
	}

	/**
	 * 返回字节流(提供下载的方法)
	 * 
	 * @param fileFileName
	 *            存储文件名
	 * @param oldName
	 *            原文件名
	 * @param where
	 *            资源位置
	 * @throws Exception
	 */
	public InputStream getDownloadStream() throws Exception {
		oldName = URLEncoder.encode(oldName, "UTF-8");
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/x-download");
		response.addHeader("Content-Disposition", "attachment;filename="
				+ oldName);
		try {
			return ServletActionContext.getServletContext()
					.getResourceAsStream(where + File.separator + fileName);
		} catch (Exception e) {
			return ServletActionContext.getServletContext()
					.getResourceAsStream("");
			
		}
	}

	/**
	 * 判断资源是否存在
	 * 
	 * @param fileName
	 *            资源名
	 * @param where
	 *            资源位置
	 * @return
	 */
	private boolean isExists(String fileName, String where) {
		if (fileName == null || "".equals(fileName) || fileName.length() == -1) {
			return false;
		}
		File file = new File(ServletActionContext.getServletContext()
				.getRealPath(where)
				+ File.separator + fileName);
		return file.exists();
	}

	public String getSql() {
		return sql;
	}

	public void setSql(String sql) {
		this.sql = sql;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public String getOldName() {
		return oldName;
	}

	public void setOldName(String oldName) {
		this.oldName = oldName;
	}

	public int getFlag() {
		return flag;
	}

	public void setFlag(int flag) {
		this.flag = flag;
	}

	public String getWhere() {
		return where;
	}

	public void setWhere(String where) {
		this.where = where;
	}
}
